package org.dtree.pv.shiro;

import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.dtree.pv.shiro.JWTToken;
import org.dtree.pv.sys.models.Sys_user;
import org.dtree.pv.sys.service.SysUserService;
import org.dtree.pv.util.JWTUtil;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service
public class MyRealm extends AuthorizingRealm{

    @Reference
    private SysUserService userService;

    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("================:::::: doGetAuthorizationInfo");
        // 根据token获取用户名
        String username = JWTUtil.getUsername(principals.toString());

        List<String> roles = userService.getRoleNamesByUsername(username);
        Set<String> permission = userService.getPermissionByUsername(username);
        System.out.println(permission);

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roles);
        simpleAuthorizationInfo.addStringPermissions(permission);
        return simpleAuthorizationInfo;
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        System.out.println("================:::::: doGetAuthenticationInfo");
        // 获取用户提交的token
        String token = (String) auth.getCredentials();
        System.out.println("================::::::"+token);
        String username = JWTUtil.getUsername(token);
        System.out.println("================::::::"+username);
        if (username == null){
            throw new AuthenticationException("token invalid");
        }

        Sys_user user = userService.getUserByUsername(username);

        if (user == null){
            throw  new AuthenticationException("User didn't existed!");
        }

        if (!JWTUtil.verify(token,username,user.getPassword())){
            throw new AuthenticationException("username or password error!");
        }

        return new SimpleAuthenticationInfo(token,token,"my_realm");

    }
}
